import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import './css/Login.css'
import { Button, Checkbox, Form, Input, message } from '@/utils/antd-imports';
import { WechatOutlined, DingdingOutlined } from '@/utils/icons'
import { useAuth } from '../context/AuthContext'
import captchaApi from '../api/captchaApi'

function Login() {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [captchaCode, setCaptchaCode] = useState('')
  const [rememberMe, setRememberMe] = useState(false)
  const [loading, setLoading] = useState(false)
  const [captchaLoading, setCaptchaLoading] = useState(false)
  const [captchaData, setCaptchaData] = useState(null)
  const navigate = useNavigate()
  const { login, isAuthenticated } = useAuth()

  // 组件挂载时生成验证码
  useEffect(() => {
    generateCaptcha()
  }, [])

  // 如果已经登录，重定向到仪表板
  useEffect(() => {
    if (isAuthenticated) {
      navigate('/dashboard')
    }
  }, [isAuthenticated, navigate])

  // 生成验证码
  const generateCaptcha = async () => {
    setCaptchaLoading(true)
    try {
      const result = await captchaApi.generateCaptcha()
      if (result.code === 200) {
        setCaptchaData(result.data)
        setCaptchaCode('') // 清空验证码输入框
      } else {
        message.error(result.message || '验证码生成失败')
      }
    } catch (error) {
      message.error('验证码生成失败，请重试')
      console.error('验证码生成错误:', error)
    } finally {
      setCaptchaLoading(false)
    }
  }

  // 输入验证函数
  const validateInput = (input) => {
    // 防止SQL注入：过滤特殊字符
    const sqlInjectionPattern = /(['";\\]|(--)|(\/\*)|(\*\/)|(xp_)|(exec)|(union)|(select)|(insert)|(update)|(delete)|(drop)|(alter)|(create))/gi
    if (sqlInjectionPattern.test(input)) {
      return false
    }
    
    // 防止XSS攻击：过滤HTML标签
    const xssPattern = /<[^>]*>?/gm
    if (xssPattern.test(input)) {
      return false
    }
    
    return true
  }

  // 处理表单提交
  const handleSubmit = async (e) => {
    if (e && e.preventDefault) {
      e.preventDefault()
    }
    
    setLoading(true)
    
    try {
      // 输入验证
      if (!validateInput(username) || !validateInput(password) || !validateInput(captchaCode)) {
        message.error('输入包含非法字符，请检查后重试')
        return
      }

      // 验证必填字段
      if (!username || !password || !captchaCode) {
        message.error('请填写完整的登录信息')
        return
      }

      if (!captchaData || !captchaData.captchaId) {
        message.error('验证码已过期，请刷新后重试')
        return
      }
      
      // 调用登录API
      const loginData = {
        username,
        password,
        captchaId: captchaData.captchaId,
        captchaCode
      }
      
      const result = await login(loginData)
      
      if (result.success) {
        if (rememberMe) {
          localStorage.setItem('rememberMe', 'true')
        }
        
        message.success('登录成功')
        navigate('/dashboard')
      } else {
        message.error(result.message || '登录失败，请检查用户名和密码')
        // 登录失败后刷新验证码
        generateCaptcha()
      }
    } catch (error) {
      message.error(error.message || '登录失败，请稍后重试')
      console.error('登录错误:', error)
      // 登录失败后刷新验证码
      generateCaptcha()
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className="login-container">
      {/* 左侧品牌区域 */}
      <div className="login-brand">
        <div className="brand-content">
          <h1>凯泽利办公系统</h1>
          <p>企业级办公解决方案</p>
        </div>
      </div>
      
      {/* 右侧登录表单 */}
      <div className="login-form-wrapper">
        <div className="login-form">
          <div className="login-header">
            <h2>欢迎登录</h2>
            <p>请输入您的账户信息</p>
          </div>
          
          <Form layout="vertical" onFinish={handleSubmit}>
            <Form.Item 
              label="用户名" 
              name="username"
              rules={[
                { required: true, message: '请输入用户名' },
                { max: 20, message: '用户名不能超过20个字符' },
                {
                  validator: (_, value) => 
                    validateInput(value) 
                      ? Promise.resolve() 
                      : Promise.reject('用户名包含非法字符')
                }
              ]}
            >
              <Input
                size="large"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                placeholder="请输入用户名"
                maxLength={20}
              />
            </Form.Item>
            
            <Form.Item 
              label="密码" 
              name="password"
              rules={[
                { required: true, message: '请输入密码' },
                { min: 6, message: '密码长度不能少于6位' },
                { max: 20, message: '密码长度不能超过20位' },
                {
                  validator: (_, value) => 
                    validateInput(value) 
                      ? Promise.resolve() 
                      : Promise.reject('密码包含非法字符')
                }
              ]}
            >
              <Input.Password
                size="large"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                placeholder="请输入密码"
                maxLength={20}
              />
            </Form.Item>

            <Form.Item 
              label="验证码" 
              name="captchaCode"
              rules={[
                { required: true, message: '请输入验证码' },
                { len: 4, message: '验证码为4位数字' },
                {
                  validator: (_, value) => 
                    validateInput(value) 
                      ? Promise.resolve() 
                      : Promise.reject('验证码包含非法字符')
                }
              ]}
            >
              <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                <Input
                  size="large"
                  value={captchaCode}
                  onChange={(e) => setCaptchaCode(e.target.value)}
                  placeholder="请输入验证码"
                  maxLength={4}
                  style={{ flex: 1 }}
                />
                <div 
                  style={{ 
                    width: '120px', 
                    height: '40px', 
                    border: '1px solid #d9d9d9', 
                    borderRadius: '6px',
                    display: 'flex', 
                    alignItems: 'center', 
                    justifyContent: 'center',
                    cursor: 'pointer',
                    backgroundColor: '#fafafa',
                    position: 'relative',
                    overflow: 'hidden'
                  }}
                  onClick={generateCaptcha}
                  title="点击刷新验证码"
                >
                  {captchaLoading ? (
                    <span style={{ color: '#999', fontSize: '12px' }}>加载中...</span>
                  ) : captchaData && captchaData.captchaImage ? (
                    <img
                      src={captchaData.captchaImage}
                      alt="验证码"
                      style={{ 
                        width: '100%', 
                        height: '100%', 
                        objectFit: 'cover',
                        cursor: 'pointer'
                      }}
                    />
                  ) : (
                    <span style={{ color: '#999', fontSize: '12px' }}>点击获取验证码</span>
                  )}
                </div>
              </div>
            </Form.Item>
            
            <Form.Item>
              <div className="form-options">
                <Checkbox
                  checked={rememberMe}
                  onChange={(e) => setRememberMe(e.target.checked)}
                >
                  记住我
                </Checkbox>
                <a href="#" className="forgot-password">忘记密码？</a>
              </div>
            </Form.Item>
            
            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                size="large" 
                block
                className="login-button"
                loading={loading}
                disabled={loading}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
          
          <div className="login-footer">
            <div className="divider">
              <span>或</span>
            </div>
            <div className="social-login">
              <Button className="social-button wechat" icon={<WechatOutlined />}>
                微信登录
              </Button>
              <Button className="social-button dingtalk" icon={<DingdingOutlined />}>
                钉钉登录
              </Button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Login